import { on, off } from '@/vuego/utils/dom';
import { renderThumbStyle, BAR_MAP } from './util';

/* istanbul ignore next */
export default {
  name: 'Bar',

  props: {
    vertical: Boolean,
    size: String,
    move: Number,
  },

  computed: {
    bar() {
      if (this.vertical) {
        return BAR_MAP.vertical;
      }
      return BAR_MAP.horizontal;
    },
    wrap() {
      return this.$parent.wrap;
    },
  },

  render() {
    const { size, move, bar } = this;

    return (
      <div
        class={ ['v-scrollbar__bar', `is-${bar.key}`] }
        onMousedown={ this.clickTrackHandler } >
        <div
          ref="thumb"
          class="v-scrollbar__thumb"
          onMousedown={ this.clickThumbHandler }
          style={ renderThumbStyle({ size, move, bar }) }>
        </div>
      </div>
    );
  },

  methods: {
    clickThumbHandler(e) {
      this.startDrag(e);
      const direction = e.currentTarget.getBoundingClientRect()[this.bar.direction];
      const offset = e[this.bar.client] - direction;
      this[this.bar.axis] = e.currentTarget[this.bar.offset] - offset;
    },

    clickTrackHandler(e) {
      const direction = e.target.getBoundingClientRect()[this.bar.direction];
      const offset = Math.abs(direction - e[this.bar.client]);
      const thumbHalf = (this.$refs.thumb[this.bar.offset] / 2);
      const thumbPositionPercentage = ((offset - thumbHalf) * 100) / this.$el[this.bar.offset];

      this.wrap[this.bar.scroll] = (thumbPositionPercentage * this.wrap[this.bar.scrollSize]) / 100;
    },

    startDrag(e) {
      e.stopImmediatePropagation();
      this.cursorDown = true;

      on(document, 'mousemove', this.mouseMoveDocumentHandler);
      on(document, 'mouseup', this.mouseUpDocumentHandler);
      document.onselectstart = () => false;
    },

    mouseMoveDocumentHandler(e) {
      if (this.cursorDown === false) return;
      const prevPage = this[this.bar.axis];

      if (!prevPage) return;

      const direction = this.$el.getBoundingClientRect()[this.bar.direction];
      const offset = (direction - e[this.bar.client]) * -1;
      const thumbClickPosition = (this.$refs.thumb[this.bar.offset] - prevPage);
      const thumbPosition = offset - thumbClickPosition;
      const thumbPositionPercentage = (thumbPosition * 100) / this.$el[this.bar.offset];

      this.wrap[this.bar.scroll] = (thumbPositionPercentage * this.wrap[this.bar.scrollSize]) / 100;
    },

    mouseUpDocumentHandler() {
      this.cursorDown = false;
      this[this.bar.axis] = 0;
      off(document, 'mousemove', this.mouseMoveDocumentHandler);
      document.onselectstart = null;
    },
  },

  destroyed() {
    off(document, 'mouseup', this.mouseUpDocumentHandler);
  },
};
